#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 crane <crane@crane-pc>
#
# Distributed under terms of the MIT license.


g_lock_entity = 0


def lock_util(lock_entity):
    # origin和to是局部变量
    origin = 0
    to = 1


    # cas理解为cpu指令, 逻辑等价于如下代码顺序执行并且不被打断.
    # if lock_entity == origin:
    #     lock_entity, to = to, lock_entity

    # 如果lock_entity为0, lock_entity == origin, 会导致lock_entity, to = to, lock_entity, 也就是lock_entity = 1, to = 0
    # 如果lock_entity为1, cas指令什么都没敢, 因为lock_entity != origin
    cas lock_entity origin to

    if origin == to:    # 拿锁成功了, lock_entity被成功设置为了1(如果拿锁没成功, 说明lock_entity已经被别人设置为1)
        return True

    return False

def release_util(lock_entity):
    lock_entity = 0



# test可能被多个线程执行
def test():
    lock(g_lock_entity)


